package com.qf.jdbcdemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1. 加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2. 获取 数据库连接对象
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
        Connection conn = DriverManager.getConnection(url, "root", "123456");
        // 关闭自动提交模式，即开启了一个事务
        // 如果以这种方式开始了事务，需要后续以 conn.commit方式提交，或者conn.rollback方式回滚才能结束事务
        conn.setAutoCommit(false);
        PreparedStatement preparedStatement = null;
        try {
            //3. 获取 Statement对象
            String sql = "INSERT INTO test VALUES (NULL,0)";
            preparedStatement= conn.prepareStatement(sql);

            //4. 执行语句
            int i = preparedStatement.executeUpdate();

            int a = 1/0;

            //5. 处理结果
            System.out.println("影响的行数"+i);
            conn.commit(); // 提交事务
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback();//回滚事务
        } finally {
            //6. 关闭资源对象
            preparedStatement.close();
            conn.close();
        }

    }
}
